package com.skydoves.chatgpt.feature.chat.ddd.messages

import android.app.Application
import android.util.Log
import androidx.compose.runtime.mutableStateMapOf
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import com.example.core_database.entities.ChatMessage
import com.example.core_database.database.AppDatabase
import com.skydoves.chatgpt.feature.chat.ddd.bots.BotRepository
import kotlinx.coroutines.launch
import javax.inject.Inject
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import androidx.core.app.NotificationCompat
import android.os.Build
import com.skydoves.chatgpt.feature.chat.R


class ChatMessagesViewModel @Inject constructor(
  application: Application,
  botId: String,
): AndroidViewModel(application) {

  private val chatMessageRepository:ChatMessageRepository
  private val botRepository:BotRepository
  // 定义一个 MutableStateMap 存储每个 bot 的消息列表
  private val _messagesMap = mutableStateMapOf<String, MutableStateFlow<List<ChatMessage>>>()
  val messagesMap: Map<String, StateFlow<List<ChatMessage>>>
    get() = _messagesMap


  private val channelId = "message_notification_channel"
  private val notificationId = 1


  init {
    createNotificationChannel()
    val chatMessageDao=AppDatabase.getDatabase(application).chatMessageDao()
    val botDao=AppDatabase.getDatabase(application).botDao()
    chatMessageRepository=ChatMessageRepository(chatMessageDao,botId)
    botRepository=BotRepository(botDao)
    //初始化message
    val chatMessagesFlow=chatMessageRepository.ChatMessages
    viewModelScope.launch {
      chatMessagesFlow.collect { messages ->
        // 更新对应 botId 的消息列表
        val currentFlow = _messagesMap[botId] ?: MutableStateFlow(emptyList())

        currentFlow.value = messages
        _messagesMap[botId]= currentFlow
      }

    }

  }

  private fun createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      val name = "消息通知"
      val descriptionText = "展示新消息通知"
      val importance = NotificationManager.IMPORTANCE_HIGH
      val channel = NotificationChannel(channelId, name, importance).apply {
        description = descriptionText
      }
      // 注册渠道
      val notificationManager: NotificationManager =
        getApplication<Application>().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
      notificationManager.createNotificationChannel(channel)
    }
  }

  fun addMessage(botId: String, newMessage: ChatMessage,botName:String) {
    Log.d("insert message", "message content: ${newMessage}")
    chatMessageRepository.insert(newMessage)
    botRepository.updateNewMessage(botId,newMessage)
    Log.d("update","new message content${newMessage.messageContent}")
    val currentList = _messagesMap[botId]?.value ?: emptyList()
    _messagesMap[botId]?.value = currentList + newMessage

    if(!newMessage.isSentByUser){
      Log.i("tctc",newMessage.messageContent)
      sendNotification(newMessage,botName)
    }

  }

  private fun sendNotification(message: ChatMessage,botName:String) {
    val notificationManager = getApplication<Application>().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    val builder = NotificationCompat.Builder(getApplication(), channelId)
      .setSmallIcon(R.drawable.smile)  // 替换为你项目中的图标
      .setContentTitle("${botName}给你发消息了")
      .setContentText(message.messageContent)
      .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    notificationManager.notify(notificationId, builder.build())
  }


  fun getMessages(botId: String): StateFlow<List<ChatMessage>> {
    return _messagesMap.getOrPut(botId) { MutableStateFlow(emptyList()) }
  }



}

class ChatMessagesViewModelFactory(
  private val application: Application,
  private val botId: String,
) : ViewModelProvider.Factory {
  override fun <T : ViewModel> create(modelClass: Class<T>): T {
    if (modelClass.isAssignableFrom(ChatMessagesViewModel::class.java)) {
      return ChatMessagesViewModel(application, botId) as T
    }
    throw IllegalArgumentException("Unknown ViewModel class")
  }
}
